SHELL := /bin/bash

get-command = $(shell which="$$(which $(1) 2> /dev/null)" && if [[ ! -z "$$which" ]]; then printf %q "$$which"; fi)

DOCKER 		:= $(call get-command,docker)
GO 			:= $(call get-command,go)

VERSION  := $(shell git describe --exact-match --tags 2>/dev/null)
REVISION := $(shell git rev-parse --short HEAD)
GOFILES  ?= $(shell git ls-files '*.go' | grep -v vendor/)
GOFMT 	 ?= $(shell gofmt -l -s $(GOFILES))

ifndef VERSION
	VERSION = latest
endif

LDFLAGS := $(LDFLAGS) -X main.revision=$(REVISION) -X main.version=$(VERSION)

all: clean test-all build docker upload

.PHONY: fmt
fmt:
	@gofmt -s -w $(GOFILES)

.PHONY: fmtcheck
fmtcheck:
	@echo $(GOFMT)
	@if [ ! -z "$(GOFMT)" ]; then \
		echo "[ERROR] gofmt has found errors in the following files:"  ; \
		echo "$(GOFMT)" ; \
		echo "" ;\
		echo "Run make fmt to fix them." ; \
		exit 1 ;\
	fi

vet:
	@echo 'go vet $$(go list ./... | grep -v ./vendor/)'
	@go vet $$(go list ./... | grep -v ./vendor/) ; if [ $$? -ne 0 ]; then \
		echo ""; \
		echo "go vet has found suspicious constructs. Please remediate any reported errors"; \
		echo "to fix them before submitting code for review."; \
		exit 1; \
	fi

test-all: fmt vet
	go test -v ./...

# build binary
build:
	@echo "Building totally static linux binary for lux-server ......"
	GOOS=linux \
	GOARCH=amd64 \
	go build -ldflags "$(LDFLAGS)" -o ./bin/eastlake ./cmd/*.go

# docker build
.PHONY: docker
docker: build
	docker build --rm -t louiswei/eastlake:$(VERSION) .

push:
	docker push louiswei/eastlake:$(VERSION)

.PHONY: clean
clean:
	rm -rf ./bin/eastlake
